import React, {Component} from 'react';

import {
    View,
    Text,
    ListView,
    StyleSheet,
    RefreshControl,
    DeviceEventEmitter
} from 'react-native';

import {THEMECOLOR} from "../../config/main";
import DataRepository, {FLAG_STORAGE} from "../../expand/Dao/DataRepository";
import TrendingCell from '../../common/TrendingCell'

export default class TrendingTab extends Component {

    constructor(props) {
        super(props)
        this.state = {
            isLoading : false,
            keyword   : '',
            dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
        }
    }

    componentDidMount() {
        this.onLoad(this.props.timeSpan, true)
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.timeSpan !== this.props.timeSpan) {
            this.onLoad(nextProps.timeSpan, true)
        }
    }

    onLoad(timeSpan, isRefresh) {
        this.setState({
            isLoading: true
        })
        let url = `https://github.com/trending/${this.props.keyword}`
        if (timeSpan && timeSpan.searchText) {
            url += `?${timeSpan.searchText}`
        }

        this.DataRepository = new DataRepository(FLAG_STORAGE.flag_trending)
        this.DataRepository.fetch(url)
            .then(result => {
                this.setState({
                    dataSource: this.state.dataSource.cloneWithRows(result),
                    isLoading : false
                })
                if (result && result.update_time && !this.DataRepository.checkData(result.update_time)) {
                    DeviceEventEmitter.emit('showToast', '数据过时')
                    return this.DataRepository.fetchNetRepository(url)
                } else {
                    DeviceEventEmitter.emit('showToast', '显示缓存数据')
                }
            })
            .then(result => {
                this.setState({
                    dataSource: this.state.dataSource.cloneWithRows(result),
                })
                DeviceEventEmitter.emit('showToast', '显示网络数据')
            })
            .catch(e => {
                console.log(e)
            })
    }

    onRefresh() {
        this.onLoad(this.props.timeSpan, true)
    }

    render() {
        return (
            <View style={{flex: 1}}>
                <ListView
                    dataSource={this.state.dataSource}
                    renderRow={(data) => <TrendingCell data={data} {...this.props}/>}
                    refreshControl={<RefreshControl
                        refreshing={this.state.isLoading}
                        onRefresh={() => {
                            this.onRefresh()
                        }}
                        colors={[THEMECOLOR]}
                        tintColor={THEMECOLOR}
                        title='加载中...'
                        titleColor={THEMECOLOR}
                    />}
                />
            </View>
        )
    }
}

const styles = StyleSheet.create({})